package com.kefu.call.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kefu.call.model.*;
import com.kefu.call.service.*;
import com.kefu.call.http.CtiClient;
import com.kefu.call.util.ResponseUtil;
import com.kefu.call.vo.CallGatewayBindVo;
import com.kefu.common.exception.BusinessException;
import com.kefu.common.mybatis.Order;
import com.kefu.sys.model.SysTenant;
import com.kefu.sys.service.SysTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kefu.common.controller.AbstractBaseController;
import com.kefu.common.result.Result;
import com.kefu.common.result.ResultGenerator;
import com.kefu.common.vo.DeleteVo;
import com.kefu.common.vo.DetailVo;
import com.kefu.call.vo.CallGatewaySearchVo;
import com.kefu.call.vo.CallGatewayInsertVo;
import com.kefu.call.vo.CallGatewayUpdateVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Api(tags = "网关表")
@RestController
@RequestMapping("call/gateway")
public class CallGatewayController extends AbstractBaseController {

    @Autowired
    private CallGatewayService callGatewayService;
    @Autowired
    CurlProfileService curlProfileService;
    @Autowired
    CtiClient ctiClient;
    @Autowired
    SysTenantService sysTenantService;
    @Autowired
    CdrCustomerService cdrCustomerService;
    @Autowired
    CdrSetmealService cdrSetmealService;
    @Autowired
    CallCompanyService callCompanyService;

    @PostMapping("/add")
    @ApiOperation(value = "新增网关表", notes = "新增网关表")
    public Result<String> add(@Validated @RequestBody CallGatewayInsertVo callGatewayVo) {
        logger.info("新增网关表:{}", callGatewayVo);

        CallGateway info = callGatewayVo.convert();
        callGatewayService.save(info);
        ctiClient.rescanSofia(info.getName());
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除网关表", notes = "删除网关表")
    public Result<String> delete(@Validated @RequestBody DeleteVo delete) {
        logger.info("删除网关表:{}", delete);
        if (StrUtil.isNotBlank(callGatewayService.getById(delete.getId()).getCompany())) {
            throw new BusinessException("请先解绑公司");
        }

        // 删除网关配置
        callGatewayService.deleteById(delete.getId());
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改网关表", notes = "修改网关表")
    public Result<String> update(@Validated @RequestBody CallGatewayUpdateVo vo) {
        logger.info("修改网关表:{}", vo);
        CallGateway db = callGatewayService.getById(vo.getFOid());// 从数据库中获取网关信息
        String company = vo.getCompany();
        if (db.getSetmealoid() != null && vo.getSetmealoid() != null) {
            if (StrUtil.isNotBlank(db.getRentalminute()) || StrUtil.isNotBlank(db.getConsumption())) {
                if (!Objects.equals(vo.getSetmealoid(), db.getSetmealoid())) {
                    throw new BusinessException("当月套餐已经生效，不能再修改当月套餐");
                }
            }
        }
        //绑定企业
        if (StrUtil.isBlank(db.getCompany()) && StrUtil.isNotBlank(company)) {
            CdrCustomer cdrCustomer = cdrCustomerService.getOne(Wrappers.lambdaQuery(CdrCustomer.class).eq(CdrCustomer::getCompany, company));
            if (cdrCustomer == null) {
                //生成计费客户
                QueryWrapper<CdrCustomer> query = Wrappers.query();
                query.select("COALESCE(max(oid),1000) oid");
                Integer maxOid = cdrCustomerService.getOne(query).getOid();
                String companyName = sysTenantService.getById(company).getTenantName();
                cdrCustomerService.save(CdrCustomer.builder().oid(maxOid+1).company(company).name(companyName).build());
                //生成呼叫公司配置
                CallCompany callCompany = callCompanyService.getOne(Wrappers.lambdaQuery(CallCompany.class).eq(CallCompany::getFid, company));
                if(callCompany == null){
                    callCompanyService.save(CallCompany.builder().fid(company).fName(companyName).build());
                }
            }
            if(StrUtil.isBlank(db.getSynctime())){
                vo.setSynctime(DateUtil.date().toString("yyyy-MM"));
            }
        }
        //解绑企业
        if ("".equals(company)) {
        }

        CallGateway info = vo.convert();
        callGatewayService.update(info);
        ctiClient.rescanSofia(db.getName());
        return ResultGenerator.genSuccessResult();
    }

    // 线路分配和解绑
    @PostMapping("/lineBind")
    @ApiOperation(value = "线路分配和解绑", notes = "线路分配和解绑")
    public Result<String> update(@Validated @RequestBody CallGatewayBindVo vo) {
        logger.info("线路绑定:{}", vo);
        List<String> fOid = vo.getFOid();


        // 解绑企业
        // 查询所有包含当前企业的线路，然后与列表fOid进行对比，如果不在列表中，则解绑
        List<CallGateway> list = callGatewayService.list(Wrappers.lambdaQuery(CallGateway.class).like(CallGateway::getCompany, vo.getTenantId()));
        list.forEach(item -> {
            if (!fOid.contains(item.getFOid())) {
                String company = item.getCompany();
                company = company.replace(vo.getTenantId(), "");
                company = company.replace(",,", ",");
                if (company.startsWith(",")) {
                    company = company.substring(1);
                }
                if (company.endsWith(",")) {
                    company = company.substring(0, company.length() - 1);
                }
                CallGateway info = new CallGateway();
                info.setFOid(item.getFOid());
                info.setCompany(company);
                callGatewayService.update(info);
                ctiClient.rescanSofia(item.getName());
            }
        });

        // 批量绑定：遍历fOid
        fOid.forEach(oid -> {
            CallGateway db = callGatewayService.getById(oid);// 从数据库中获取网关信息
            if (!StrUtil.isBlank(db.getCompany())) {
                // 此时的db.getCompany()是一个逗号分割的字符串，包含了多个company，判断是否包含vo.getTenantId()
                if (db.getCompany().contains(vo.getTenantId())) {
                    // 中断循环，遍历下一个fOid
                    return;
                }
            }
            String company = vo.getTenantId();
            //绑定企业
            if ((StrUtil.isBlank(db.getCompany()) || !db.getCompany().contains(vo.getTenantId())) && StrUtil.isNotBlank(company)) {
                CdrCustomer cdrCustomer = cdrCustomerService.getOne(Wrappers.lambdaQuery(CdrCustomer.class).eq(CdrCustomer::getCompany, company));
                if (cdrCustomer == null) {
                    //生成计费客户
                    QueryWrapper<CdrCustomer> query = Wrappers.query();
                    query.select("COALESCE(max(oid),1000) oid");
                    Integer maxOid = cdrCustomerService.getOne(query).getOid();
                    String companyName = sysTenantService.getById(company).getTenantName();
                    cdrCustomerService.save(CdrCustomer.builder().oid(maxOid + 1).company(company).name(companyName).build());
                    //生成呼叫公司配置
                    CallCompany callCompany = callCompanyService.getOne(Wrappers.lambdaQuery(CallCompany.class).eq(CallCompany::getFid, company));
                    if (callCompany == null) {
                        callCompanyService.save(CallCompany.builder().fid(company).fName(companyName).build());
                    }
                }
            }
            CallGateway info = new CallGateway();
            info.setFOid(oid);
            company = StrUtil.isBlank(db.getCompany()) ? company : db.getCompany() + "," + company;
            info.setCompany(company);
            if (StrUtil.isBlank(db.getSynctime())) {
                info.setSynctime(DateUtil.date().toString("yyyy-MM"));
            }
            callGatewayService.update(info);
            ctiClient.rescanSofia(db.getName());

        });

        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/detail")
    @ApiOperation(value = "网关表详情", notes = "网关表详情")
    public Result<CallGateway> detail(@Validated @RequestBody DetailVo detail) {

        CallGateway callGateway = callGatewayService.findById(detail.getId());
        return ResultGenerator.genSuccessResult(callGateway);
    }

    @PostMapping("/list")
    @ApiOperation(value = "查询网关表", notes = "查询网关表")
    public Result<Page<CallGateway>> list(@Validated @RequestBody CallGatewaySearchVo search) {

        search.setOrderField("fOid");
        search.setOrder(Order.DESC);
        Page<CallGateway> page = callGatewayService.searchLambdaPage(search);

        // 使用sysTenantService查询出所有的企业，并且组成一个map，key是tenantId，value是tenantName
        Map<String, String> tenantMap = sysTenantService.list().stream().collect(Collectors.toMap(SysTenant::getTenantId, SysTenant::getTenantName));
        logger.info("--tenantMap:{}", tenantMap);


        page.getRecords().forEach(item -> {
            // 如果当前item中的getCompany()不为空，那么就使用逗号分割，然后遍历，使用tenantMap获取tenantName，然后拼接
            if (StrUtil.isNotBlank(item.getCompany())) {
                String[] companyArray = item.getCompany().split(",");
                StringBuilder sb = new StringBuilder();
                for (String company : companyArray) {
                    sb.append(tenantMap.get(company)).append(",");
                }
                // 移除最后一个逗号
                sb.deleteCharAt(sb.length() - 1);
                item.setCompanyName(sb.toString());
            }

            Optional.ofNullable(item.getSetmealoid()).map(i -> cdrSetmealService.getById(i)).ifPresent(i -> item.setSetmealName(i.getName()));
            Optional.ofNullable(item.getSetmealoidU()).map(i -> cdrSetmealService.getById(i)).ifPresent(i -> item.setSetmealNameU(i.getName()));
        });
        return ResultGenerator.genSuccessResult(page);
    }

    @PostMapping("/reloadFsMod")
    @ApiOperation(value = "重新加载")
    public void reloadFsMod(HttpServletResponse response) {
        ResponseUtil.responseJson(response,ResultGenerator.genSuccessResult());
        logger.info("刷新freeswitch模块");
    }


}
